package mblog.web.job;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import mblog.core.data.User;
import mblog.core.persist.dao.UserDao;
import mblog.core.persist.entity.UserPO;
import mblog.core.persist.service.UserService;
import mtons.modules.pojos.Paging;
@Controller
public class MblogPost {
	@Autowired
	public static UserDao userDao;
	@Autowired
    private static UserService userService;
	static String tysSpiderLogDir = "/data/luoshSpiderLog/";
	// 本次连接
	static int loginTimeLimit = 0;
																	// SESSION
	static String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0";
	static String[] USERS = new String[]{"2","3","4","6","7","9","10","11","12","13","14","16","18","19","20","21","28","29","30","31","36","37","38","39","40","42","43","44","45","46","48","49","50","51","52","53","55","57","58","61","62","66","67","68","69","70","71","74","75","77","78","85","86","87","88","89","91","93","94","97","98","99","100","105","107","260","391","399","410"};
	static Random r = new Random();  
	static int randomKey = r.nextInt(USERS.length);
	@Test
	public void maintest() throws IOException {
		for (int k = 1; k < 2; k++) {
			Map<String, String> artcle = new HashMap<>();
			artcle.put("content", "分享您我的时落事往！" + k);
			artcle.put("title", "分享您我的时落事往！" + k);
			artcle.put("tags", "落事");
			artcle.put("summary", new Date()+"");
			post(artcle);
		}
	}

	// http://localhost:8080/mblog/post/submit2?group=1&editor=ueditor&summary=2015%252D07%252D20%252019%253A36%253A24&title=tttttt1&privacy=0&content=ccccccc1&tags=%25E4%25BF%25A1%25E7%2594%25A8%25E5%258D%25A1%252C%25E5%25BE%2581%25E4%25BF%25A1
	public static Boolean postReal(Map<String, String> artcle) throws Exception {
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).setUserAgent(userAgent)
				.build();
		try {

			NameValuePair[] nvpsArr = new NameValuePair[artcle.size() + 1];
			int k = 0;
			for (Map.Entry<String, String> a : artcle.entrySet()) {
				if ("content".equals(a.getKey())) {
					if (a.getValue().startsWith("管理员")) {
						nvpsArr[k++] = new BasicNameValuePair("privacy", "1");// 列为私密
					} else {
						nvpsArr[k++] = new BasicNameValuePair("privacy", "0");
					}
				}
				nvpsArr[k++] = new BasicNameValuePair(a.getKey(), (/*new URLEncoder().encode(*/a.getValue()));
			}

			HttpUriRequest login = RequestBuilder.post()
					.setUri(new URI("http://localhost:8088/post/submit2"))
					.addParameter("group", "1")
					.addParameter("editor", "ueditor")
					.addParameters(nvpsArr).build();

			CloseableHttpResponse response2 = httpclient.execute(login);
			try {
				HttpEntity entity = response2.getEntity();

				System.out.println("Login form get: " + response2.getStatusLine());
				EntityUtils.consume(entity);

				// 是否未登录
				
				if (needLogin) {
					loginMblog();
					postReal(artcle);// 递归调用一次
				}

				System.out.println("Post logon cookies:");
				List<Cookie> cookies = cookieStore.getCookies();
				if (cookies.isEmpty()) {
					throw new RuntimeException("登录失败呢，怎么回事");
				} else {
					// for (int i = 0; i < cookies.size(); i++) {
					// System.out.println("- " + cookies.get(i).toString());
					// }
				}
			} finally {
				response2.close();
			}
		} finally {
			httpclient.close();
		}
		return null;
	}

	public static Boolean post(Map<String, String> artcle) {
		String srcUrl = artcle.get("srcUrl") + "";
		artcle.remove("srcUrl");
		try {
			postReal(artcle);
		} catch (Exception e) {
			e.printStackTrace();
			manmalArticle(srcUrl);
		}
		return false;

	}
	static boolean needLogin =true;
	static BasicCookieStore cookieStore = new BasicCookieStore();
	public static synchronized void loginMblog() throws Exception {
		System.out.println("开始自动登录，次数" + loginTimeLimit);
		if (loginTimeLimit++ > 5) {
			throw new RuntimeException("5次都登录失败了，还不停下");
		}

		CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).setUserAgent(userAgent)
				.build();
		try {
			/*
			 * HttpGet httpget = new HttpGet("http://localhost:8080/ltySys/");
			 * CloseableHttpResponse response1 = httpclient.execute(httpget);
			 * try { HttpEntity entity = response1.getEntity();
			 * 
			 * System.out.println("Login form get: " +
			 * response1.getStatusLine()); EntityUtils.consume(entity);
			 * 
			 * System.out.println("Initial set of cookies:"); List<Cookie>
			 * cookies = cookieStore.getCookies(); if (cookies.isEmpty()) {
			 * System.out.println("None"); } else { for (int i = 0; i <
			 * cookies.size(); i++) { System.out.println("- " +
			 * cookies.get(i).toString()); } } } finally { response1.close(); }
			 */
			HttpUriRequest login = null;
				login = RequestBuilder.post().setUri(new URI("http://localhost:8088/login"))
						.addParameter("username", "caoyingde").addParameter("password", "802321").build();

				CloseableHttpResponse response2 = httpclient.execute(login);
				try {
					HttpEntity entity = response2.getEntity();
	
					System.out.println("Login form get: " + response2.getStatusLine());
					EntityUtils.consume(entity);
	
					System.out.println("Post logon cookies:");
					List<Cookie> cookies = cookieStore.getCookies();
					if (cookies.isEmpty()) {
						throw new RuntimeException("登录失败呢，怎么回事");
					} else {
						// for (int i = 0; i < cookies.size(); i++) {
						// System.out.println("- " + cookies.get(i).toString());
						// }
						needLogin=false;
					}
				} finally {
					response2.close();
				}
		} finally {
			httpclient.close();
		}
		
	}
	/**
	 * 记录需要手动的文章URL
	 * 
	 * @param url
	 * @return
	 */
	static Boolean manmalArticle(String url) {
		String fileName = "mblog_err.txt";

		try {
			File f = new File(tysSpiderLogDir + fileName);
			FileUtils.writeStringToFile(f, url + "\n", true);
		} catch (IOException e) {
			//e.printStackTrace();
		}
		return false;
	}
}
